console.log(Vue);

var ctrylist = ['Abknazia', 'Adygea', 'Afghanistan', 'Ajaria', 'Aland', 'Albania', 'Alderney', 'Algeria', 'Altai-Republic', 'American-Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua-and-Barbuda', 'Argentina',
	'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Bashkortostan', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bikini-Atoll', 'Bolivia', 'Bosnia-and-Herze-govina,Federation-OF',
	'Bosnia-and-Herzegovina', 'Botswana', 'Brazil', 'British-Antarctic-Territory', 'British-Indian-Ocean-Territory', 'Brittany', 'Brunei', 'Bulgaria', 'Burkina-Faso', 'Burundi', 'Buryatia', 'Cambodia', 'Cameroon', 'Canada',
	'Cape-Verde', 'Cayman-Islands', 'Central-African-Republic', 'Chad', 'Chechen-Repub-lic-of-lchkeria', 'Chechen-Repub-lic', 'Chile', 'China', 'Christmas-Island', 'Chuvashia', 'Colombia', 'Comoros', 'Congo,Democratic-Republic-of-the',
	'Congo,Republic-of-the', 'Cook-Islands', 'Costa-Rica', 'Cote-d,lvoire', 'Crimea', 'Croatia', 'Cuba', 'Cyprus', 'Czech-Republic', 'Dagestan', 'Denmark', 'Djibouti', 'Dominica', 'Dominican-Republic', 'East-Timor', 'Easter-Island-Rapa-Nui',
	'Ecuador', 'Egypt', 'EL-Salvador', 'England', 'Equatorial-Guinea', 'Eritea', 'Estonia', 'Ethiopia', 'European-Union', 'Falkland-Islands', 'Faroe-Islands', 'Fiji', 'Finland', 'France', 'French-Polynesia', 'French-Southern-and-Antarctic-Lands',
	'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guam', 'Guatemala', 'Guernsey', 'Guinea-Bissau', 'Guinea', 'Guyana', 'Haiti', 'Herm', 'Honduras', 'Hong-Kong', 'Hungary', 'Iceland', 'India',
	'Indonesia', 'Ingushetia', 'Iran', 'Iraq', 'Ireland', 'Isleofman', 'Israel', 'Italy', 'jamaica', 'japan', 'jersey', 'jordan', 'kabardino-balkaria', 'kalmykia', 'karachay-cherkessia', 'karakalpakstan', 'karelia', 'kazakhstan', 'kenya', 'khakassia',
	'kiribati', 'komi', 'korea,north', 'korea,south', 'kosovo', 'Kuban--peoples--republic', 'kuwait', 'kyrgyzstan', 'Ladonia', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Los-Altos', 'Luxembourg',
	'Macau', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Mari-El', 'Marshall-Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia,Federated-States', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro',
	'Montserrat', 'Mordovia', 'Morocco', 'Mozambique', 'Myanmar-Burma', 'Nagorno-Karabakh-Republic', 'Namibia', 'Nauru', 'Nepal', 'Netherlands-Antilles', 'Netherlands', 'New-Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue',
	'Norfolk-Island', 'North-Ossetia', 'Northern-Mari-ana-Islands', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine', 'Panama', 'Papua-New-Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcairn-Islands', 'Poland', 'Portugal', 'Puerto-Rico',
	'Qatar', 'Republika-Srpska', 'Romania', 'Russia', 'Rwanda', 'Saba', 'Saint-Barthelemy', 'Saint-Helena', 'Saint-Kitts-and-Nevis', 'Saint-Lucia', 'Saint-Martin', 'Saint-Pierre-and-Miquelon', 'Saint-Vincent-and-the-Grenadines',
	'Sakha-Republic', 'Samoa', 'San-Marino', 'Sao-Tome-and-Principe', 'Sark', 'Saudi-Arabia', 'Sealand-Principality-of', 'Senegal', 'Serbia', 'Seychelles', 'Sierra-Leone', 'Sikkim', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon-Islands',
	'Somalia', 'Somaliland', 'South-Africa', 'South-Georgia-and-the-South-Sandwich-Islands', 'South-Ossetia', 'Sovereign-Military-Order-of-Malta', 'Spain', 'Sri-Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Swutzerland',
	'Syria', 'Tajikistan', 'Tanzania', 'Tatarstan', 'Thailand', 'Tierra-del-Fuego-Province-Argentina', 'Togo', 'Tokelau', 'Tonga', 'Transnistria', 'Trinidad-and-Tobago', 'Tristan-da-Cunha', 'Tunisia', 'Turkey', 'Turkis-Republic-of-Northern-Cyprus',
	'Turkmenistan', 'Turks-and-Caicos-lslands', 'Tuva', 'Tuvalu', 'Udmurtia', 'Uganda', 'Ukraine', 'United-Arab-EMirates', 'United-Kingdom', 'United-STates', 'Uruguay', 'Uzbekistan', 'Virgin-Islands-UK', 'Virgin-Islands-US',
	'Wales', 'Western-Sahara', 'Yemen', 'Zambia', 'Zinmbabwe'];

var starData = {
	'mercury': { 'ename': 'Mercury', 'cname': '水星', 'volume': '3.3022×10²³kg', 'mass': '4878km', 'user': '', 'nick': '', 'price': '', 'imgname': 'shuixing', 'id': 0, 'gyun': '00'},
	'venus': { 'ename': 'Venus', 'cname': '金星', 'volume': '4.869×10²⁴kg', 'mass': '12103.6km', 'user': '', 'nick': '', 'price': '', 'imgname': 'jinxing', 'id': 0, 'gyun': '00'},
	'mars': { 'ename': 'Mars', 'cname': '火星', 'volume': '6.4219×10²³kg', 'mass': '6794km', 'user': '', 'nick': '', 'price': '', 'imgname': 'huoxing', 'id': 0, 'gyun': '00'},
	'jupiter': { 'ename': 'Jupiter', 'cname': '木星', 'volume': '1.90×10²⁷kg', 'mass': '142987km', 'user': '', 'nick': '', 'price': '', 'imgname': 'muxing', 'id': 0, 'gyun': '00'},
	'saturn': { 'ename': 'Saturn', 'cname': '土星', 'volume': '5.688×10²⁶kg', 'mass': '120540㎞', 'user': '', 'nick': '', 'price': '', 'imgname': 'tuxing', 'id': 0, 'gyun': '02'},
	'uranus': { 'ename': 'Uranus', 'cname': '天王星', 'volume': '8.6810 ±13×10²⁵kg', 'mass': '51118km', 'user': '', 'nick': '', 'price': '', 'imgname': 'tianwangxing', 'id': 0, 'gyun': '01'},
	'neptune': { 'ename': 'Neptune', 'cname': '海王星', 'volume': '1.0247×10²⁶kg', 'mass': '49,532km', 'user': '', 'nick': '', 'price': '', 'imgname': 'haiwangxing', 'id': 0, 'gyun': '00'},
	'pluto': { 'ename': 'Pluto', 'cname': '冥王星', 'volume': '1.305±0.007×10²²kg', 'mass': '2375km', 'user': '', 'nick': '', 'price': '', 'imgname': 'mingwangxing', 'id': 0, 'gyun': '00'},
	'charon': { 'ename': 'Charon', 'cname': '卡戎（冥衛一）', 'volume': '1.90×10²¹kg', 'mass': '1208km', 'user': '', 'nick': '', 'price': '', 'imgname': 'kajie', 'id': 0, 'gyun': '00'},
	'ceres': { 'ename': 'Ceres', 'cname': '穀神星', 'volume': '9.43±0.07×10²⁰ kg', 'mass': '950km', 'user': '', 'nick': '', 'price': '', 'imgname': 'gushenxing', 'id': 0, 'gyun': '00'},
	'eris': { 'ename': 'Eris', 'cname': '鬩神星', 'volume': '(1.66 ± ）×10^22kg', 'mass': '2326±12km', 'user': '', 'nick': '', 'price': '', 'imgname': 'eris', 'id': 0, 'gyun': '00'},
	'makemake': { 'ename': 'Makemake', 'cname': '鳥神星', 'volume': '4×10²¹ kg', 'mass': '1781km', 'user': '', 'nick': '', 'price': '', 'imgname': 'niaoshenxing', 'id': 0, 'gyun': '00'},
	'haumea': { 'ename': 'Haumea', 'cname': '妊神星', 'volume': '4.2×10²¹ kg', 'mass': '1436km', 'user': '', 'nick': '', 'price': '', 'imgname': 'gushenxing', 'id': 0, 'gyun': '00'},
	'io': { 'ename': 'Io', 'cname': '伊俄（木衛一）', 'volume': '8.9319×10²² kg', 'mass': '3637.4km', 'user': '', 'nick': '', 'price': '', 'imgname': 'yie', 'id': 0, 'gyun': '00'},
	'europa': { 'ename': 'Europa', 'cname': '歐羅巴（木衛二）', 'volume': '4.80×10²² kg', 'mass': '3138km', 'user': '', 'nick': '', 'price': '', 'imgname': 'ouluoba', 'id': 0, 'gyun': '00'},
	'ganymede': { 'ename': 'Ganymede', 'cname': '蓋尼米得（木衛三）', 'volume': '1.4819×10²³ kg', 'mass': '5264km', 'user': '', 'nick': '', 'price': '', 'imgname': 'gainimide', 'id': 0, 'gyun': '00'},
	'callisto': { 'ename': 'Callisto', 'cname': '卡里斯托（木衛四）', 'volume': '1.08 x 10²³ kg', 'mass': '4800km', 'user': '', 'nick': '', 'price': '', 'imgname': 'kalisituo', 'id': 0, 'gyun': '00'},
	'titan': { 'ename': 'Titan', 'cname': '泰坦（土衛六）', 'volume': '(1.3452±0.0002)×1023 kg', 'mass': '5150km', 'user': '', 'nick': '', 'price': '', 'imgname': 'taitan', 'id': 0, 'gyun': '00'},
	'triton': { 'ename': 'Triton', 'cname': '特賴登（海衛一）', 'volume': '2.147×10²²kg', 'mass': '2706.8±1.8 km', 'user': '', 'nick': '', 'price': '', 'imgname': 'telaideng', 'id': 0, 'gyun': '00'},
	'moon': { 'ename': 'The Moon', 'cname': '月球', 'volume': '7.349×10²²kg', 'mass': '3476.28km', 'user': '', 'nick': '', 'price': '', 'imgname': 'yueqiu', 'id': 0, 'gyun': '00'}
}

var nicklist = {};

var userlist = [
	{ name: 'aaaa', count: '2', price: '0.22' },
	{ name: 'bbb', count: '2', price: '0.21' },
	{ name: 'ccc', count: '2', price: '0.12' },
	{ name: 'ddd', count: '2', price: '0.22' },
	{ name: 'eee', count: '2', price: '0.22' },
	{ name: 'fff', count: '2', price: '0.22' },
	{ name: '张三', count: '2', price: '0.22' },
	{ name: '五王', count: '2', price: '0.22' },
	{ name: '哈哈', count: '2', price: '0.22' }
]

var timer = null;
var app = new Vue({
	el: '#app',
	data: {
		lge: language,
		lgename: i18n.map[lang],
		ranklist: [], // 排行榜列表
		starlist: [], // 星球列表
		dataList: [], // 数据列表
		myDataList: [], // 我的数据列表
		hoveruser: '', // hover星球用户
		elem: {}, // 当前选中星球
		buyinfo: {}, // 购买信息
		time: 0, // 定时时间
		account: account, // 当前帐号
		load: true, // load
		ctrylist: ctrylist, // 国旗列表
		nick: '', // 当前昵称
		ctryid: '999', // 当前国籍ID
		nickshow: false, // 昵称显示
		nickprice: 1000000000000000, // 默认当前价格
		online: false, // 连接状态
		sortName: '', // 排序方式
		isMyStar: false 
	},
	updated: function() {
		$('.s-group').popover();
		var stars = $('#yzhou div').popover();
		// jq hover
		stars.hover(function() {
			stars.addClass('op');
			$(this).removeClass('op')
		}, function() {
			stars.removeClass('op')
		});
	},
	methods: {
		setlanguage: function(ln) {
			this.lge = i18n[ln];
			this.lgename = i18n.map[ln];
			localStorage.lang = ln;
		},
		eth: function(num){ // eth 格式转换
			if (!num) return '';
			var eth = num/1000000000000000000;
			return eth.toFixed(6);
		},
		getNick: function(){ // 获取昵称
			this.nick = this.account.toLocaleUpperCase().substr(this.account.length-6, 100);
			var that = this;
			instance = web3.eth.contract(abix2018).at(adrx2018);
			instance.accountOfN.call(this.account, function(i,  name) {
				if(name == ''){
					that.nick = that.account.toLocaleUpperCase().substr(that.account.length-6, 100);
					return ;
				}
				that.nick = name;
			});
			instance.accountOfP.call(this.account, function(i, price) {
				if(price != 0){
					that.nickprice = price * 2;
				}
			});
			instance.countryofN.call(this.account, function(i, ctry) {
				if(ctry){
					that.ctryid = ctry;
				}
			})
		},
		buy: function(elem) { // 进入购买详情
			if(elem.user == this.account){
				alert(this.lge.alter3);
				return;
			}
			var that = this;
			console.log('buyinfo:', elem);
			this.elem = elem;
			$('#myModal').modal();
			this.refreshInfo();
		},
		buyok: function() { // 确认购买
			var that = this;
			instance = web3.eth.contract(abix2018).at(adrx2018);
			
			var config = {
				from: this.account,
				value: this.buyinfo.nprice,
				gas: 100000 // 固定gas
			};
			console.log(this.elem.id, config);
			instance.buy.sendTransaction(this.elem.id, config, function(err, val) {
				if(err) {
					console.log(err);
					return  alert(that.lge.alter1);
				};
				console.log(val);
				that.refreshInfo();
				//https://ropsten.etherscan.io/tx/' + val + '
			});
//			let rawTx = {
//              from: web3.eth.coinbase,
//              value: web3.sha3(this.buyinfo.nprice)
//          };
//          
//			web3.eth.getGasPrice(function(a, gas){
//				console.log(a, gas.c);
//				rawTx.gasPrice = gas.c[0]//web3.sha3(gas.c[0])
//				
//				web3.eth.getBlock('latest', (function(a, block){
//					rawTx.gasLimit = web3.sha3(block.gasLimit);
//					console.log(block.gasLimit);
//					
//					web3.eth.estimateGas(rawTx, function(a, gas){
//						console.log(gas);
//						that.buyByGas(gas*2);
//					})
//				}))
//			})
		},
		refreshInfo: function(){
			var that = this;
			this.load = true;
			this.getToken(this.elem.id.toString(), function(token) {
				console.log('token:', token);
				that.load = false;
				token.ename =that.elem.ename;
				token.cname =that.elem.cname;
				token.imgname = that.elem.imgname;
				token.nick = that.elem.nick;
				token.ctryid = that.elem.ctryid;
				that.buyinfo = token;
				that.settimer();
			})
		},
		settimer: function() {
			var that = this;
			that.time = 0;
			clearInterval(timer);
			timer = setInterval(function() {
				that.time++;
			}, 1000);
		},
		enter: function(user) {
			this.hoveruser = user;
		},
		leave: function() {
			this.hoveruser = '';
		},
		isme: function(name, sname) {
			if(name == '') return false;
			if(name === sname) return false;
			return true;
		},
		getToken: function(f, fn) {
			var that = this;
			var i = 6;
			var obj = {};
			instance = web3.eth.contract(abix2018).at(adrx2018);
			instance.startingPriceOf.call(f, function(g, h) {
				obj.sprice = h + '';
				if(that.getTokenover(i--)) fn(obj);
			});
			instance.priceOf.call(f, function(g, h) {
				obj.nprice = h + '';
				if(that.getTokenover(i--)) fn(obj);
			});
			instance.ownerOf.call(f, function(g, h) {
				obj.user = h
				if(that.getTokenover(i--)) fn(obj);
			});
			instance.nextPriceOf.call(f, function(g, h) {
				obj.next = h + '';
				if(that.getTokenover(i--)) fn(obj);
			});
			instance.itemNameOf.call(f, function(g, h) {
				console.log('tokenname:', h, f);
				obj.name = h ? Utils.hexCharCodeToStr(h) : '';
				if(that.getTokenover(i--)) fn(obj);
			});
			instance.itemNameAddress.call(f, function(g, h) {
				obj.ads = h
				if(that.getTokenover(i--)) fn(obj);
			})
		},
		getTokenover: function(num) {
			if(num-- == 1) {
				return true;
			}
		},
		changectry: function(id, pole){
			var str = pole ? 'pole/flag_' : '/';
			return '../icon/flag'+str+this.ctrylist[parseInt(id)]+'.png';
		},
		selectCtry: function(id){
			var _index = id > 99 ? id : (id > 9 ? '0'+id : '00'+id);
			this.ctryid = _index;
		},
		setUserInfo: function(){
			var that = this;
			instance = web3.eth.contract(abix2018).at(adrx2018);
			var param = {
				value: this.nickprice
			};
			console.log('setnick:', this.nick, this.ctryid, param);
			instance.setNick.sendTransaction(this.nick, this.ctryid+'', param, function(err, order) {
				if (err) { console.log(err); return alert(that.lge.alter1);};
				console.log('hash %s', order);
				alert(that.lge.alter2);
			});
		},
		getNickByToken: function(token, fn){
			var nick = token.user.toLocaleUpperCase().substr(token.user.length-6, 100);
			token.nick = nick;
			token.ctryid = '999';
			var that = this;
			var len = 2;
			instance = web3.eth.contract(abix2018).at(adrx2018);
			instance.accountOfN.call(token.user, function(i,  name) {
				if(name){
					token.nick = name;
				}
				if(--len == 0){fn()}
			});
			instance.countryofN.call(token.user, function(i, ctry) {
				if(ctry){
					token.ctryid = ctry;
				}
				if(--len == 0){fn()}
			});
		},
		init: function(el) {
			this.online = true;
			// id对应token 顺序
			var arr = tokenidArr;
			var len = arr.length;
			var datalist = [];
			//
			for (var i=0; i<arr.length; i++) {
				var that = this;
				// nickobj
				;(function(id){
					that.getToken(id, function(token){
						if(token.name == ''){ // token 为空表示获取失败，该星球不显示
							if(--len === 0){
								maketop(datalist);
							}
							return;
						}
						token.id = id;
						datalist.push(token);
						that.getNickByToken(token, function(){
							if(--len === 0){
								maketop(datalist);
							}
						})
					});
				})(arr[i]);
			}
		},
		changeSort: function(type, sortname){ // 排序规则
			this.sortName = sortname || this.lge.raise;
			switch(type){
				case 1: 
				this.dataList = this.dataList.sort(function(n1, n2){
					return n2.price - n1.price;
				});break;
				case 2: 
				this.dataList = this.dataList.sort(function(n1, n2){
					return n1.price - n2.price;
				});break;
			}
		},
		reloadPage: function(btn){
			this.isMyStar = btn;
		}
	},
	watch: {
		account: function(val, oldVal){
			console.log('setNick new: %s', val);
			if(val.length > 20){
				this.getNick();
				this.init();
				this.nickshow = true;
			} else {
				app.starlist = starData;
			}
		}
	}
})

// $('.s-yzbox').hover(function(){
//   $('#yzhou').removeClass('run')
// },
// function(){
//   $('#yzhou').addClass('run')
// })

// token 提取数据
var t1 = { user: '0xbc1a9c9461aee2681fa8ebdec5481263509794fa', name: '0x6d6f6f6e7c000000000000000000000000000000000000000000000000000000', next: 2105263157894736, nprice: 1000000000000000, sprice: 1000000000000000, ads: '0xbc1a9c9461aee2681fa8ebdec5481263509794fa' }
var t2 = { user: '0xbc1a9c9461aee2681fa8ebdec5481263509794fa', name: '0x76656e7573000000000000000000000000000000000000000000000000000000', next: 2105263157894736, nprice: 1000000000000000, sprice: 1000000000000000, ads: '0xbc1a9c9461aee2681fa8ebdec5481263509794fa' }
var t3 = { user: '0x7e9b53b7f0b75ee4e34c8c7833b41b8ff96666d2', name: '0x6d6f6f6e00000000000000000000000000000000000000000000000000000000', next: 2105263157894736, nprice: 1000000000000000, sprice: 1000000000000000, ads: '0xbc1a9c9461aee2681fa8ebdec5481263509794fa' }

// var tokens = [t1];

var maketop = function(tokens) { // 组装页面数据列表
	console.log(tokens)
	var arr = [];
	var jsn = {};
	var dataList = [];
	var myDataList = [];
	for(var i = 0; i < tokens.length; i++) {
		// rank
		var item = tokens[i];
		if (item.user !== owner) { // ranklist
			if(jsn[tokens[i].user]) {
				var arritem = arr[jsn[tokens[i].user] - 1];
				arritem.count++;
				arritem.price = arritem.price*1 + item.nprice*1;
			} else {
				arr.push({
					user: item.user,
					count: 1,
					price: item.nprice,
					nick: item.nick,
					ctryid: item.ctryid
				});
				jsn[item.user] = arr.length;
			}
		} else {
			item.nick = 'blank';
		}
		// star
		// var name = Utils.hexCharCodeToStr(item.user);
		// 星球列表数据
		var sitem = starData[item.name];
		sitem.price = item.nprice;
		sitem.user = item.user;
		sitem.id = item.id;
		sitem.ctryid = item.ctryid;
		sitem.nick = item.nick;
		dataList.push(sitem);
		if(item.user === app.account){
			myDataList.push(sitem);
		}
	};
	arr = arr.sort(function(n1, n2){
		return n2.price - n1.price;
	});
	app.ranklist = arr;
	app.starlist = starData;
	app.dataList = dataList;
	app.myDataList = myDataList;
	app.online = false;
	app.changeSort(1);
}
app.starlist = starData;

// router
app.isMyStar = location.hash.substring(1) === 'mystar';
//console.log(userlist, maketop())
window.addEventListener('hashchange', function(){
	app.reloadPage(location.hash.substring(1) === 'mystar');
});